const http = require("http");
const path = require("path");
const fs = require("fs");
const cheerio = require("cheerio");
var filePath = path.join(__dirname, "/movie.html");
var content = fs.readFileSync(filePath);
content = content.toString("utf-8");

var $ = cheerio.load(content);
var arr = [];

$(".channel-detail.movie-item-title a").each((i, el) => {
    var obj = {};
    obj.movieId = $(el).attr("data-val").toString().split(":")[1].slice(0, -1);
    obj.movieName = $(el).text();
    arr.push(obj);
});
$(".channel-detail.channel-detail-orange").each((i, el) => {
    arr[i]["movieOrange"] = $(el).text();
});

var filePath1 = path.join(__dirname, "/index.html");

http.createServer((req, res) => {
    var jurl = req.url;
    if (jurl == "/") {
        res.writeHead(200, { "Content-Type": "text/html" });
        var fileContent = fs.readFileSync(filePath1);
        res.write(fileContent);
        res.end();
    } else if (jurl == "/getlist") {
        var jsonString = JSON.stringify(arr);
        res.writeHead(200, { "Content-Type": "text/plain;charset=utf-8" });
        res.write(jsonString);
        res.end();
    }
}).listen(8080);
console.log("listening on port 8080");
